package test.yzx.pproject.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Looper;
import android.support.annotation.ColorInt;
import android.support.annotation.IntRange;
import android.util.AttributeSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.FrameLayout;

public class HomeRingPercentView extends FrameLayout {

    public HomeRingPercentView(Context context) {
        this(context, null);
    }
    public HomeRingPercentView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public HomeRingPercentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }
    private void init(){
        setWillNotDraw(false);
        post(new Runnable() {
            public void run() {
                hasViewPosted = true;
            }
        });
    }



    private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private int halfViewLength;
    private int progressWidth;
    private RectF progressRect;
    private final int progressPadding = dp2px(9);
    private ValueAnimator mAnimator;
    private int animDuration = 1500;
    private final Interpolator interpolator = new DecelerateInterpolator();

    @Override
    protected void onDraw(Canvas canvas) {
        /* draw background circle */
        canvas.save();
        canvas.translate(halfViewLength, halfViewLength);
        paint.setColor(bgCircleColor);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawCircle(0, 0, halfViewLength, paint);
        canvas.restore();
        /* draw progress background */
        canvas.save();
        paint.setColor(progressBgColor);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(progressWidth);
        if(progressRect == null){
            float start = progressPadding+paint.getStrokeWidth()/2;
            float end = getWidth() - start;
            progressRect = new RectF(start, start, end, end);
        }
        canvas.drawArc(progressRect, 0, 360, false, paint);
        canvas.restore();
        /* draw progress */
        canvas.save();
        paint.setColor(getColorByProgress(animProgress/X));
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(progressWidth);
        canvas.drawArc(progressRect, -270, animProgress*360f/MAX, false, paint);
        canvas.restore();
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        halfViewLength = getWidth()>>1;
        progressWidth = getWidth()/11;
    }
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        endAnim();
    }
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        if(getChildCount()>1)
            throw new IllegalStateException(getClass().getSimpleName() + " only can hold one child~");
        super.onLayout(changed, left, top, right, bottom);
    }


    /* .. */
    private void makeProgressAnim(){
        endAnim();
        mAnimator = ValueAnimator.ofInt(oldProgress, currentProgress).setDuration(animDuration);
        mAnimator.setInterpolator(interpolator);
        mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                int now = (int) animation.getAnimatedValue();
                if(now == animProgress)
                    return ;
                animProgress = now;
                invalidateIfNeeded();
            }
        });
        mAnimator.addListener(new AnimatorListenerAdapter(){
            public void onAnimationEnd(Animator animation) {
                animProgress = oldProgress = currentProgress;
                mAnimator = null;
                if(onAnimEndListener != null) onAnimEndListener.onEnd(HomeRingPercentView.this);
            }
        });
        mAnimator.start();
    }
    private void endAnim(){
        if(mAnimator != null){
            mAnimator.end();
            mAnimator = null;
        }
    }
    /* .. */
    private void invalidateIfNeeded(){
        if(!hasViewPosted) return ;
        if(Looper.getMainLooper() == Looper.myLooper()) invalidate();
        else postInvalidate();
    }
    /* .. */
    private int dp2px(int dp){
        return (int) (getResources().getDisplayMetrics().density*dp+0.5f);
    }
    /* 根据进度值获取应该显示的颜色 */
    private int getColorByProgress(int progress){
        if(progress <= levelSplit[0])
            return progressColors[0];
        if(progress <= levelSplit[1])
            return progressColors[1];
        return progressColors[2];
    }



    private OnAnimEndListener onAnimEndListener;
    private boolean hasViewPosted = false;

    private int bgCircleColor = Color.parseColor("#333333");
    private int[] progressColors = {Color.RED, Color.YELLOW, Color.BLUE};
    private int[] levelSplit = { 40, 70 };
    private int progressBgColor = Color.parseColor("#777777");

    private final int X = 10000;
    private final int MAX = 100 * X;
    private int oldProgress;
    private int currentProgress;
    private int animProgress;


    /** 设置背景颜色 */
    public void setBgCircleColor(@ColorInt int bgCircleColor) {
        this.bgCircleColor = bgCircleColor;
        invalidateIfNeeded();
    }
    /** 设置进度条颜色 */
    public void setProgressBgColor(@ColorInt int progressBgColor) {
        this.progressBgColor = progressBgColor;
        invalidateIfNeeded();
    }
    /** 设置进度条背景颜色: {Color.RED, Color.YELLOW, Color.BLUE} */
    public void setProgressColors(@ColorInt int[] progressColors){
        this.progressColors = progressColors;
        invalidateIfNeeded();
    }
    /** 设置三个级别的分割值:  { 40, 70 } */
    public void setLevelSplit(int[] splitArray){
        this.levelSplit = splitArray;
        invalidateIfNeeded();
    }
    /** 设置进度 0 - 100
     * @param anim 是否执行过度动画
     * */
    public void setProgress(@IntRange(from = 0, to = 100) int p, boolean anim){
        this.currentProgress = p * X;
        if(anim)
            makeProgressAnim();
        else{
            animProgress = oldProgress = currentProgress;
            invalidateIfNeeded();
        }
    }
    /** 获取当前进度 */
    public int getCurrentProgress(){
        return this.currentProgress / X;
    }
    /** 设置动画结束回调, 仅setProgress()第二个参数为true时有效 */
    public void setOnAnimEndListener(OnAnimEndListener onAnimEndListener) {
        this.onAnimEndListener = onAnimEndListener;
    }
    /** get 动画时长 */
    public int getAnimDuration() {
        return animDuration;
    }
    /** set 动画时长 */
    public void setAnimDuration(int animDuration) {
        this.animDuration = animDuration;
    }
    /** 是否在动画中 */
    public boolean inAnim(){
        return mAnimator != null && mAnimator.isRunning();
    }




    public interface OnAnimEndListener{
        void onEnd(HomeRingPercentView view);
    }

}
